

function say() {
    alert("LC:224. 基本计算器");
}
say();

/**
 * @param {string} s
 * @return {number}
 */
var calculate = function(s) {
  //10:14-24 //10:57-11:15
  //字符串处理
  var arr = string2Arr(s)
  if(arr.length == 1){
    return parseInt(arr[0])
  }

  var numStack = [], opStack = []

  for(var i = 0; i < arr.length; i++){
    var item = arr[i]
    if(item == '('){
      opStack.push(item)
    }else if(item == '+' || item == '-'){ //判空, 左括号,直接push
      if(opStack.length == 0 || opStack[opStack.length - 1] == '('){
        
      }else {
        var yunSuan = opStack.pop()
        myCalculate(numStack, yunSuan)
      }
      opStack.push(item)
    }else if(item == ')'){ //循环,直到找到左括号
      var yunSuan = opStack.pop()
      while(typeof(yunSuan) != 'undefined' && yunSuan != '('){
        myCalculate(numStack, yunSuan)
        yunSuan = opStack.pop()
      }
    }else { //数字
      numStack.push(parseInt(item))
    }
  }

  //处理最后
  // console.log('最后',numStack,'op:',opStack)
 
  var yunSuan = opStack.pop()
  myCalculate(numStack, yunSuan)
  return numStack.pop()
};

function myCalculate (numStack, yunSuan){
  var lastNum = numStack.pop()
  var preNum = numStack.pop()
  preNum = typeof (preNum) == 'undefined' ? 0 : preNum
  if(yunSuan == '-'){
    numStack.push(preNum - lastNum)
  }else {
    numStack.push(preNum + lastNum)
  }
}

function string2Arr(string){ //TODO:优化,不转数组,在循环里面处理
  string = string.split(' ').join('')
  string = string.split('(+').join('(0+')
  string = string.split('(-').join('(0-')

  // console.log('字符串',string)
  var arr = []
  for(var i = 0; i < string.length; i++){
    var item = string.charAt(i)
    if(item == '+' || item == '-' || item == '(' || item == ')'){
      arr.push(item)
      
    }else { //数字
      var gap = 1
      while(i + gap < string.length && isNum(string.charAt(i + gap))){
        gap++
      }
      var target = string.slice(i, i + gap)
      arr.push(target)
      i = i + gap - 1
    }
  }

  return arr
}

function isNum(string){
  if(string.charCodeAt(0) >= '0'.charCodeAt(0) && string.charCodeAt(0) <= '9'.charCodeAt(0)){
    return true
  }else {
    return false
  }
}
